package com.codeoss.module.res.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codeoss.framework.util.ValueNamePair;
import com.codeoss.module.res.model.ResRelUserRole;
import com.codeoss.module.res.model.ResRole;
import com.codeoss.module.res.request.RelUserRolePageRequest;
import com.codeoss.module.res.response.RelUserRolePageResponse;
import com.codeoss.module.res.service.IRelUserRolePageService;
import com.codeoss.module.res.service.IResRelUserRoleService;
import com.codeoss.module.res.service.IResRoleService;

@Service
public class RelUserRolePageService implements IRelUserRolePageService {
    @Autowired
    private IResRoleService resRoleService;
    @Autowired
    private IResRelUserRoleService resRelUserRoleService;
	@Override
	public RelUserRolePageResponse init(Long resUserId) {
		// TODO Auto-generated method stub
		RelUserRolePageResponse relUserRolePageResponse=new RelUserRolePageResponse();
		List<ValueNamePair> roleList=new ArrayList<ValueNamePair>();
		relUserRolePageResponse.setRoleList(roleList);
		List<ResRole> resRoleList=resRoleService.list();
		for(ResRole resRole:resRoleList) {
			ValueNamePair pair=new ValueNamePair(resRole.getName(),resRole.getId());
			roleList.add(pair);
		}
		List<Long> valueList=resRelUserRoleService.getRoleIdListByUserId(resUserId);
		relUserRolePageResponse.setValueList(valueList);
		return relUserRolePageResponse;
	}
	
	@Override
	@Transactional
	public RelUserRolePageResponse dataSave(RelUserRolePageRequest request) {
		// TODO Auto-generated method stub
		RelUserRolePageResponse relUserRolePageResponse=new RelUserRolePageResponse();
		QueryWrapper<ResRelUserRole> queryWrapper=new QueryWrapper<ResRelUserRole>();
		queryWrapper.eq("res_user_id", request.getResUserId());
		resRelUserRoleService.remove(queryWrapper);
		List<Long> valueList=request.getValueList();
		if(valueList!=null) {
			for(int i=0;i<valueList.size();i++) {
				ResRelUserRole resRelUserRole=new ResRelUserRole();
				resRelUserRole.setResUserId(request.getResUserId());
				resRelUserRole.setResRoleId(valueList.get(i));
				resRelUserRoleService.insert(resRelUserRole);
			}
		}
		return relUserRolePageResponse;
	}

}
